package com.zcbl.toolkit.util;

import com.zcbl.toolkit.exception.SystemRuntimeException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.Assert;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;

/**
 * @author He Peng
 * @create 2018-04-06 11:37
 * @update 2018-04-06 11:37
 * @updatedesc : 更新说明
 * @see
 */
public class EnumUtils {

    private EnumUtils() {}

    public static <T extends Enum<T>> T getEunmInstance(Class<T> eunmClass , Object obj , String fieldName) {
        Assert.notNull(eunmClass , "eunmClass == null");
        Assert.notNull(obj , "obj == null");
        Assert.hasLength(fieldName , "fieldName is blank");
        if (! eunmClass.isEnum()) {
            return null;
        }
        List<T> enumList = org.apache.commons.lang3.EnumUtils.getEnumList(eunmClass);
        if (CollectionUtils.isEmpty(enumList)) {
            return null;
        }

        try {
            for (T em : enumList) {
                Field field = em.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Object val = field.get(em);
                if (obj instanceof Number && val instanceof Number) {
                    obj = obj + "";
                    val = val + "";
                }
                if (Objects.equals(val , obj)) {
                    return em;
                }
            }
        } catch (Exception e) {
            throw new SystemRuntimeException(e.getMessage() , e);
        }
        return null;
    }
}
